package com.zp95sky.cloud.starter.knife4j.micro.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.zp95sky.cloud.starter.knife4j.micro.properties.SwaggerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Swagger 配置文件
 * @author 华夏紫穹
 */
@Configuration
@EnableSwagger2
@EnableKnife4j
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerConfiguration {

    @Bean
    public Docket createRestApi(SwaggerProperties properties) {
        if (ObjectUtils.isEmpty(properties)) {
            return new Docket(DocumentationType.SWAGGER_2);
        }

        Docket docket = new Docket(DocumentationType.SWAGGER_2);
        docket.apiInfo(apiInfo(properties));

        if (StringUtils.isEmpty(properties.getBasePackage())) {
            return docket;
        }

        return docket.select().
                apis(RequestHandlerSelectors.basePackage(properties.getBasePackage()))
                .paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo(SwaggerProperties properties) {
        if (ObjectUtils.isEmpty(properties)) {
            return ApiInfo.DEFAULT;
        }

        SwaggerProperties.ContactProperties contactProperties = properties.getContact();
        Contact contact;
        if (! ObjectUtils.isEmpty(contactProperties)) {
            contact = new Contact(properties.getContact().getName(),
                    properties.getContact().getUrl(), properties.getContact().getEmail());
        } else {
            contact = ApiInfo.DEFAULT_CONTACT;
        }

        ApiInfoBuilder build = new ApiInfoBuilder();

        if (! StringUtils.isEmpty(properties.getTitle())) {
            build.title(properties.getTitle());
        }

        if (! StringUtils.isEmpty(properties.getDescription())) {
            build.description(properties.getDescription());
        }

        build.contact(contact);

        if (! StringUtils.isEmpty(properties.getVersion())) {
            build.version(properties.getVersion());
        }

        return build.build();
    }

}
